package org.marsdonne.commons.jpa;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;

@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper=false)
public class StringFieldFilter extends BasedFieldFilter {
    private String value;

    public StringFieldFilter(Operator operator, String value) {
        this.operator = operator;
        this.value = value;
    }

    @Override
    public Predicate generateCriteria(CriteriaBuilder builder, Path field) {
        switch (operator) {
            case eq:
                return builder.equal(field, value);
            case endsWith:
                return builder.like(field, "%" + value);
            case startsWith:
                return builder.like(field, value + "%");
            case contains:
                return builder.like(field, "%" + value + "%");
            case ne:
                return builder.notEqual(field, value);
            default:
                return null;
        }
    }
}
